package week9

import (
	"encoding/binary"
	"fmt"
	"net"
	"os"
	"os/signal"
)

func main() {
	server := "127.0.0.1:8080"

	tcpAddr, err := net.ResolveTCPAddr("tcp4", server)

	if err != nil {
		fmt.Fprintf(os.Stderr, "错误:%s", err.Error())
		os.Exit(1)
	}

	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		fmt.Fprintf(os.Stderr, "错误: %s", err.Error())
		os.Exit(1)
	}

	defer conn.Close()
	fmt.Println("连接成功")

	go decoder(conn)

	//合建chan
	c := make(chan os.Signal)
	//监听指定信号 ctrl+c kill
	signal.Notify(c, os.Interrupt, os.Kill)
	//阻塞直到有信号传入
	fmt.Println("启动")
	//阻塞直至有信号传入
	s := <-c
	fmt.Println("退出信号", s)
}

func decoder(conn net.Conn) {
	packLenBytes := make([]byte, 4)
	conn.Read(packLenBytes)

	packLength := binary.BigEndian.Uint32(packLenBytes)

	msg := make([]byte, packLength-4)

	conn.Read(msg)

	headerLenBytes := msg[0:2]
	headerLen := binary.BigEndian.Uint32(headerLenBytes)
	//header := msg[0:headerLen]

	protocolVersion := msg[2:4]
	opertion := msg[4:8]
	sid := msg[8:12]

	body := msg[headerLen-4:]

	handle(protocolVersion, opertion, sid, body)
}

func handle(protocolVersion []byte, opertion []byte, sid []byte, body []byte) {

}
